<template>
  <div class="smart-search">
    <div class="search-container">
      <!-- 搜索输入框 -->
      <div class="search-input-section">
        <el-input
          v-model="searchKeyword"
          size="large"
          placeholder="输入您的问题，AI将为您智能匹配最相关的答案..."
          @keyup.enter="handleSearch"
          class="search-input"
        >
          <template #prepend>
            <el-icon><Search /></el-icon>
          </template>
          <template #append>
            <el-button type="primary" @click="handleSearch" :loading="searching">
              智能搜索
            </el-button>
          </template>
        </el-input>
        
        <!-- 搜索配置 -->
        <div class="search-config">
          <el-row :gutter="16">
            <el-col :span="8">
              <el-form-item label="匹配阈值:">
                <el-slider
                  v-model="searchConfig.matchThreshold"
                  :min="0.1"
                  :max="1"
                  :step="0.1"
                  show-tooltip
                  :format-tooltip="formatThreshold"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="结果数量:">
                <el-input-number
                  v-model="searchConfig.limit"
                  :min="1"
                  :max="20"
                  size="small"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="快速搜索:">
                <el-switch v-model="searchConfig.quickSearch" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </div>

      <!-- 搜索建议 -->
      <div v-if="!searchResults.length && !searching" class="search-suggestions">
        <h3>热门搜索</h3>
        <div class="suggestion-tags">
          <el-tag
            v-for="suggestion in hotSuggestions"
            :key="suggestion"
            @click="selectSuggestion(suggestion)"
            class="suggestion-tag"
          >
            {{ suggestion }}
          </el-tag>
        </div>
        
        <h3>搜索技巧</h3>
        <ul class="search-tips">
          <li>使用具体的关键词描述您的问题</li>
          <li>可以用自然语言提问，如"如何退换货？"</li>
          <li>调整匹配阈值来控制搜索结果的精确度</li>
          <li>使用快速搜索可以获得更快的响应速度</li>
        </ul>
      </div>

      <!-- 搜索结果 -->
      <div v-if="searchResults.length" class="search-results">
        <div class="results-header">
          <h3>搜索结果 ({{ searchResults.length }} 条)</h3>
          <el-button type="text" @click="clearResults">
            <el-icon><Close /></el-icon>
            清空结果
          </el-button>
        </div>
        
        <div class="results-list">
          <div
            v-for="(result, index) in searchResults"
            :key="index"
            class="result-item"
          >
            <div class="result-header">
              <div class="result-title">
                <h4>{{ result.title }}</h4>
                <div class="result-meta">
                  <el-tag size="small" :type="getCategoryType(result.category)">
                    {{ getCategoryLabel(result.category) }}
                  </el-tag>
                  <span class="match-score">
                    匹配度: {{ Math.round(result.matchScore * 100) }}%
                  </span>
                </div>
              </div>
              <div class="result-actions">
                <el-button type="text" size="small" @click="expandResult(index)">
                  {{ expandedResults.includes(index) ? '收起' : '展开' }}
                </el-button>
                <el-button type="text" size="small" @click="useAsAnswer(result)">
                  使用答案
                </el-button>
              </div>
            </div>
            
            <div class="result-question">
              <strong>问题：</strong>{{ result.question }}
            </div>
            
            <div
              v-if="expandedResults.includes(index)"
              class="result-answer"
            >
              <strong>答案：</strong>
              <div class="answer-content" v-html="result.answer"></div>
              
              <div v-if="result.relatedLinks" class="related-links">
                <strong>相关链接：</strong>
                <a :href="result.relatedLinks" target="_blank">{{ result.relatedLinks }}</a>
              </div>
              
              <div v-if="result.tags" class="result-tags">
                <strong>标签：</strong>
                <el-tag
                  v-for="tag in result.tags.split(',')"
                  :key="tag"
                  size="small"
                  class="tag-item"
                >
                  {{ tag.trim() }}
                </el-tag>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 搜索历史 -->
      <div v-if="searchHistory.length" class="search-history">
        <div class="history-header">
          <h3>搜索历史</h3>
          <el-button type="text" size="small" @click="clearHistory">
            清空历史
          </el-button>
        </div>
        <div class="history-list">
          <div
            v-for="(history, index) in searchHistory"
            :key="index"
            class="history-item"
            @click="selectHistory(history)"
          >
            <el-icon><Clock /></el-icon>
            <span class="history-keyword">{{ history.keyword }}</span>
            <span class="history-time">{{ formatTime(history.timestamp) }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 使用答案对话框 -->
    <el-dialog v-model="showAnswerDialog" title="使用答案" width="60%">
      <div v-if="selectedAnswer" class="answer-preview">
        <h4>{{ selectedAnswer.title }}</h4>
        <div class="answer-content" v-html="selectedAnswer.answer"></div>
      </div>
      <template #footer>
        <el-button @click="showAnswerDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmUseAnswer">确认使用</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Close, Clock } from '@element-plus/icons-vue'
import { AICustomerService } from '@/services/aiCustomerService'

// 响应式数据
const searchKeyword = ref('')
const searching = ref(false)
const searchResults = ref<any[]>([])
const expandedResults = ref<number[]>([])
const searchHistory = ref<any[]>([])
const showAnswerDialog = ref(false)
const selectedAnswer = ref<any>(null)

// 搜索配置
const searchConfig = ref({
  matchThreshold: 0.5,
  limit: 5,
  quickSearch: false
})

// 热门搜索建议
const hotSuggestions = ref([
  '如何退换货',
  '订单查询',
  '产品保修',
  '技术支持',
  '账户问题',
  '支付方式',
  '物流配送',
  '联系客服'
])

// 初始化
onMounted(() => {
  loadSearchHistory()
})

// 执行搜索
const handleSearch = async () => {
  if (!searchKeyword.value.trim()) {
    ElMessage.warning('请输入搜索关键词')
    return
  }
  
  searching.value = true
  
  try {
    const params = {
      keyword: searchKeyword.value,
      matchThreshold: searchConfig.value.matchThreshold,
      limit: searchConfig.value.limit
    }
    
    const response = await AICustomerService.searchKnowledge(params)
    
    if (response.code === 200) {
      searchResults.value = response.data || []
      
      // 添加到搜索历史
      addToHistory(searchKeyword.value)
      
      if (searchResults.value.length === 0) {
        ElMessage.info('未找到相关结果，请尝试调整搜索关键词或降低匹配阈值')
      }
    } else {
      ElMessage.error(response.msg || '搜索失败')
    }
  } catch (error) {
    ElMessage.error('搜索失败，请稍后重试')
  } finally {
    searching.value = false
  }
}

// 选择搜索建议
const selectSuggestion = (suggestion: string) => {
  searchKeyword.value = suggestion
  handleSearch()
}

// 选择搜索历史
const selectHistory = (history: any) => {
  searchKeyword.value = history.keyword
  handleSearch()
}

// 展开/收起结果
const expandResult = (index: number) => {
  const expandedIndex = expandedResults.value.indexOf(index)
  if (expandedIndex > -1) {
    expandedResults.value.splice(expandedIndex, 1)
  } else {
    expandedResults.value.push(index)
  }
}

// 使用答案
const useAsAnswer = (result: any) => {
  selectedAnswer.value = result
  showAnswerDialog.value = true
}

// 确认使用答案
const confirmUseAnswer = () => {
  // 这里可以将答案发送到聊天界面或其他地方
  ElMessage.success('答案已应用')
  showAnswerDialog.value = false
}

// 清空结果
const clearResults = () => {
  searchResults.value = []
  expandedResults.value = []
}

// 添加到搜索历史
const addToHistory = (keyword: string) => {
  const historyItem = {
    keyword,
    timestamp: new Date()
  }
  
  // 移除重复项
  searchHistory.value = searchHistory.value.filter(item => item.keyword !== keyword)
  
  // 添加到开头
  searchHistory.value.unshift(historyItem)
  
  // 限制历史记录数量
  if (searchHistory.value.length > 10) {
    searchHistory.value = searchHistory.value.slice(0, 10)
  }
  
  // 保存到本地存储
  localStorage.setItem('aiSearchHistory', JSON.stringify(searchHistory.value))
}

// 加载搜索历史
const loadSearchHistory = () => {
  try {
    const history = localStorage.getItem('aiSearchHistory')
    if (history) {
      searchHistory.value = JSON.parse(history)
    }
  } catch (error) {
    console.error('加载搜索历史失败:', error)
  }
}

// 清空搜索历史
const clearHistory = () => {
  searchHistory.value = []
  localStorage.removeItem('aiSearchHistory')
  ElMessage.success('搜索历史已清空')
}

// 格式化匹配阈值
const formatThreshold = (value: number) => {
  return `${Math.round(value * 100)}%`
}

// 获取分类类型
const getCategoryType = (category: string) => {
  const types: Record<string, string> = {
    product: 'primary',
    technical: 'success',
    order: 'warning',
    service: 'info',
    other: ''
  }
  return types[category] || ''
}

// 获取分类标签
const getCategoryLabel = (category: string) => {
  const labels: Record<string, string> = {
    product: '产品咨询',
    technical: '技术支持',
    order: '订单相关',
    service: '售后服务',
    other: '其他'
  }
  return labels[category] || category
}

// 格式化时间
const formatTime = (date: Date) => {
  return new Date(date).toLocaleString('zh-CN')
}
</script>

<style scoped>
.smart-search {
  padding: 20px;
  background: #f8f9fa;
  min-height: 600px;
}

.search-container {
  max-width: 800px;
  margin: 0 auto;
}

.search-input-section {
  background: white;
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.search-input {
  margin-bottom: 20px;
}

.search-config {
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.search-suggestions {
  background: white;
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.search-suggestions h3 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 16px;
}

.suggestion-tags {
  margin-bottom: 30px;
}

.suggestion-tag {
  margin: 0 8px 8px 0;
  cursor: pointer;
  transition: all 0.3s;
}

.suggestion-tag:hover {
  background: #409EFF;
  color: white;
}

.search-tips {
  margin: 0;
  padding-left: 20px;
}

.search-tips li {
  margin-bottom: 8px;
  color: #666;
  line-height: 1.5;
}

.search-results {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.results-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 30px;
  border-bottom: 1px solid #eee;
}

.results-header h3 {
  margin: 0;
  color: #333;
}

.results-list {
  padding: 0;
}

.result-item {
  padding: 20px 30px;
  border-bottom: 1px solid #f0f0f0;
}

.result-item:last-child {
  border-bottom: none;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 10px;
}

.result-title h4 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 16px;
}

.result-meta {
  display: flex;
  align-items: center;
  gap: 12px;
}

.match-score {
  font-size: 12px;
  color: #666;
}

.result-actions {
  display: flex;
  gap: 8px;
}

.result-question {
  color: #666;
  margin-bottom: 10px;
  line-height: 1.5;
}

.result-answer {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #f0f0f0;
}

.answer-content {
  margin: 10px 0;
  line-height: 1.6;
  color: #333;
}

.related-links {
  margin-top: 10px;
}

.related-links a {
  color: #409EFF;
  text-decoration: none;
}

.related-links a:hover {
  text-decoration: underline;
}

.result-tags {
  margin-top: 10px;
}

.tag-item {
  margin-right: 8px;
  margin-bottom: 4px;
}

.search-history {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 30px;
  border-bottom: 1px solid #eee;
}

.history-header h3 {
  margin: 0;
  color: #333;
}

.history-list {
  padding: 10px 0;
}

.history-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 30px;
  cursor: pointer;
  transition: background 0.3s;
}

.history-item:hover {
  background: #f8f9fa;
}

.history-keyword {
  flex: 1;
  color: #333;
}

.history-time {
  font-size: 12px;
  color: #999;
}

.answer-preview {
  padding: 20px 0;
}

.answer-preview h4 {
  margin: 0 0 15px 0;
  color: #333;
}
</style>
